package com.nd.service.wx;

import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nd.dao.CategoryMapper;
import com.nd.dao.GoodsMapper;
import com.nd.dao.KeywordMapper;
import com.nd.dao.SearchHistoryMapper;
import com.nd.pojo.bean.*;
import com.nd.pojo.vo.BaseRespVo;
import com.nd.pojo.vo.wx.BaseRespWXVo;
import com.nd.pojo.vo.wx.SelectIndexVO;
import com.nd.pojo.vo.wx.SelectResult;
import org.apache.ibatis.annotations.Select;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import java.lang.System;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: project2mall
 * @description:
 * @author: shit_code_builder
 * @create: 2021-06-08 22:07
 **/

@Service
public class SelectService {

    @Autowired
    KeywordMapper keywordMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CategoryMapper categoryMapper;

    public BaseRespWXVo index() {

        SelectIndexVO selectIndexVO = new SelectIndexVO();

        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria().andIsDefaultEqualTo(true).andDeletedEqualTo(false);
        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);
        selectIndexVO.setDefaultKeyword(keywords.get(0));

        KeywordExample keywordExample1 = new KeywordExample();
        KeywordExample.Criteria criteria1 = keywordExample1.createCriteria().andIsHotEqualTo(true).andDeletedEqualTo(false);
        List<Keyword> hotkeywords = keywordMapper.selectByExample(keywordExample1);
        selectIndexVO.setHotKeywordList(hotkeywords);
        Integer id = -1;
        try {
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
           id  = user.getId();
        }catch (Exception e){
        }

        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        searchHistoryExample.createCriteria().andUserIdEqualTo(id).andDeletedEqualTo(false);
        ArrayList<SelectIndexVO.HistoryKeywordListBean> historyKeywordListBeans = new ArrayList<>();
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        for (SearchHistory searchHistory : searchHistories) {
            SelectIndexVO.HistoryKeywordListBean historyKeywordListBean = new SelectIndexVO.HistoryKeywordListBean();
            historyKeywordListBean.setKeyword(searchHistory.getKeyword());
            historyKeywordListBeans.add(historyKeywordListBean);
        }
        selectIndexVO.setHistoryKeywordList(historyKeywordListBeans);

    return BaseRespWXVo.ok(selectIndexVO);
    }

    public BaseRespWXVo<List<String>> helper(String keyWord) {

        KeywordExample keywordExample = new KeywordExample();
        keywordExample.createCriteria().andDeletedEqualTo(false).andKeywordLike("%"+keyWord+"%");
        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);
        List<String> collect = keywords.stream().map(Keyword::getKeyword).collect(Collectors.toList());

        return BaseRespWXVo.ok(collect);
    }

    public BaseRespWXVo result(Integer categoryId, Integer page, Integer size, String keyword, String sort, String order, Boolean isHot, Boolean isNew) {
        Integer id=-1;
        try {
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
           id = user.getId();

            if (keyword!=null&& !"".equals(keyword)){
                SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
                SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria().andDeletedEqualTo(false);
                criteria.andKeywordEqualTo(keyword);
                List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
                if (searchHistories.isEmpty()) {
                    SearchHistory wx = SearchHistory.builder().userId(id).updateTime(DateTime.now()).addTime(DateTime.now()).deleted(false).from("WX").keyword(keyword).build();
                    int insert = searchHistoryMapper.insert(wx);
                }
            }
        }catch (Exception e){
            System.out.println("未登录不做搜索历史插入");
        }

        PageHelper.startPage(page,size);

        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setOrderByClause(sort+" "+order);

        GoodsExample.Criteria criteria1 = goodsExample.createCriteria();
        if (keyword!=null&&!"".equals(keyword)){
             criteria1 = criteria1.andKeywordsLike("%"+keyword+"%");
            goodsExample.or().andNameLike("%"+keyword+"%");
        }else if (isHot!=null&&isHot==true){
            criteria1.andIsHotEqualTo(true);
        }else if (isNew!=null&&isNew==true){
            criteria1.andIsNewEqualTo(true);
        }else {
            return BaseRespWXVo.fail("错误参数失败");
        }

        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        SelectResult selectResult = new SelectResult();
        List<SelectResult.GoodsListBean> goodsListBeans = new ArrayList<>();
        TreeSet categories = new TreeSet((Comparator<Category>) (o1, o2) -> o1.getId()-o2.getId());
        for (Goods good : goods) {
                if (categoryId!=0&&categoryId.compareTo(good.getCategoryId())==0){
                    SelectResult.GoodsListBean build = SelectResult.GoodsListBean.builder().brief(good.getBrief()).counterPrice(good.getCounterPrice().doubleValue()).id(good.getId()).isHot(good.getIsHot()).isNew(good.getIsNew()).name(good.getName()).picUrl(good.getPicUrl()).retailPrice(good.getRetailPrice().doubleValue()).build();
                    goodsListBeans.add(build);
                }else if (categoryId==0){
                    SelectResult.GoodsListBean build = SelectResult.GoodsListBean.builder().brief(good.getBrief()).counterPrice(good.getCounterPrice().doubleValue()).id(good.getId()).isHot(good.getIsHot()).isNew(good.getIsNew()).name(good.getName()).picUrl(good.getPicUrl()).retailPrice(good.getRetailPrice().doubleValue()).build();
                    goodsListBeans.add(build);
                }
            Category category = categoryMapper.selectByPrimaryKey(good.getCategoryId());
            categories.add(category);
        }
        PageInfo<Goods> objectPageInfo = new PageInfo<>(goods);
        long total = objectPageInfo.getTotal();

        selectResult.setCount(total);
        selectResult.setFilterCategoryList(categories);
        selectResult.setGoodsList(goodsListBeans);

        return BaseRespWXVo.ok(selectResult);
    }

    public BaseRespWXVo deletehistory() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer id = user.getId();

        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        searchHistoryExample.createCriteria().andUserIdEqualTo(id).andDeletedEqualTo(false);
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        List<SearchHistory> collect = searchHistories.stream().map((o) -> {
            o.setDeleted(true);
            return o;
        }).collect(Collectors.toList());
        for (SearchHistory searchHistory : collect) {
            searchHistoryMapper.updateByPrimaryKey(searchHistory);
        }
    return BaseRespWXVo.ok();
    }
}
